#coding=utf8
import cv2
import numpy as np
import  datetime

'''
将本地4个视频合并到一个画面

说明：
1，如果先将原始视频resize为1/2,再读取合并，2分钟视频花费110秒，比较节省时间，但是resize也比较耗时。

'''

videoLeftUp = cv2.VideoCapture(r'D:\data\test\4\1s.mp4')
videoLeftDown = cv2.VideoCapture(r'D:\data\test\4\2s.mp4')
videoRightUp = cv2.VideoCapture(r'D:\data\test\4\3s.mp4')
videoRightDown = cv2.VideoCapture(r'D:\data\test\4\4s.mp4')
#注意：要使用原视频的帧率(改变了帧率，就会改变视频的时间长度，相当于快进或慢镜头)
fps = videoLeftUp.get(cv2.CAP_PROP_FPS)


width =  (int(videoLeftUp.get(cv2.CAP_PROP_FRAME_WIDTH)))
height =   (int(videoLeftUp.get(cv2.CAP_PROP_FRAME_HEIGHT)))
# 占用空间最小的编码(windows不支持)  CV_FOURCC('M', 'P', '4', '2') = MPEG-4.2 codec
videoWriter = cv2.VideoWriter(r'D:\data\test\4\test4.mp4', cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), fps, (width, height))



successLeftUp, frameLeftUp = videoLeftUp.read()
successLeftDown , frameLeftDown = videoLeftDown.read()
successRightUp, frameRightUp = videoRightUp.read()
successRightDown, frameRightDown = videoRightDown.read()

start_time = datetime.datetime.now()
i = 0
while successLeftUp and successLeftDown and successRightUp and successRightDown:
    #resize
    frameLeftUp = cv2.resize(frameLeftUp, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    frameLeftDown = cv2.resize(frameLeftDown, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    frameRightUp = cv2.resize(frameRightUp, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    frameRightDown = cv2.resize(frameRightDown, (int(width / 2), int(height / 2)), interpolation=cv2.INTER_CUBIC)
    #merge
    frameUp = np.hstack((frameLeftUp, frameRightUp))
    frameDown = np.hstack((frameLeftDown, frameRightDown))
    frame = np.vstack((frameUp, frameDown))
    videoWriter.write(frame)
    # read
    successLeftUp, frameLeftUp = videoLeftUp.read()
    successLeftDown, frameLeftDown = videoLeftDown.read()
    successRightUp, frameRightUp = videoRightUp.read()
    successRightDown, frameRightDown = videoRightDown.read()

    print i
    i += 1
    # if i == 100:
    #     break


videoWriter.release()
videoLeftUp.release()
videoLeftDown.release()
videoRightUp.release()
videoRightDown.release()

end_time = datetime.datetime.now()
print "total_seconds:  %s" % (end_time - start_time).total_seconds()